package eu.jakubiak.javabean;

import java.util.HashMap;
import java.util.Map;

/**
 * Initializint of BeanReflector is quite time consuming
 * It's bettet to cache initialized reflectors
 * 
 * Singleton
 */
public class BeanReflactorCachedFactory implements IBeanReflectorFactory {

	/**
	 * Cached reflectors
	 */
	@SuppressWarnings("unchecked")
	private Map<Class, BeanReflector> reflectors = new HashMap<Class, BeanReflector>();
	
	
	/**
	 * Get Java Bean Reflector from cache or create new one
	 * and insert it to cache
	 */
	@SuppressWarnings("unchecked")
	public BeanReflector create(Class clazz) {
		if ( reflectors.containsKey(clazz) ) {
			return reflectors.get(clazz);
		}
		BeanReflector beanReflector = new BeanReflector(clazz);
		reflectors.put(clazz, beanReflector);
		return beanReflector;
	}


	private static BeanReflactorCachedFactory instance;
	
	/**
	 * @return Singleton
	 */
	public static IBeanReflectorFactory instance() {
		if (instance!=null) {
			return instance;
		}
		synchronized(BeanReflactorCachedFactory.class) {
			if (instance==null) {
				instance = new BeanReflactorCachedFactory();
			}
			return instance;
		}
	}


	private BeanReflactorCachedFactory() {
		super();
	}
}
	

